package com.m3958.firstgwt.server.servlet;

import java.io.File;
import java.io.IOException;
import java.io.Writer;

import javax.servlet.Servlet;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.servlet.ServletFileUpload;

import com.google.inject.Inject;
import com.google.inject.Injector;
import com.google.inject.Singleton;
import com.m3958.firstgwt.server.dao.AssetDao;
import com.m3958.firstgwt.server.model.Asset;
import com.m3958.firstgwt.server.service.AppUtilService;
import com.m3958.firstgwt.server.service.FilePathService;
import com.m3958.firstgwt.server.service.FileUploader;
import com.m3958.firstgwt.server.service.SiteConfiger;
import com.m3958.firstgwt.server.service.SiteConfiger.SiteConfigerKeyName;
import com.m3958.firstgwt.server.utils.ExecPerl;

@Singleton
public class FileUploadServlet extends HttpServlet implements Servlet{
	
	
	@Inject
	Injector injector;
	
	@Inject
	protected FilePathService fps;
	
	@Inject
	protected SiteConfiger siteConfiger;
	
	@Inject
	private AppUtilService autils;

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	
	@Override
	public void doGet(HttpServletRequest req, HttpServletResponse res)
			throws ServletException, IOException {
		res.setContentType("text/html;charset=UTF-8");   
		res.setCharacterEncoding("UTF-8");
		String assetId = req.getParameter("asset");
		AssetDao assetDao = injector.getInstance(AssetDao.class);
		Asset a = assetDao.find(Integer.parseInt(assetId));
		String size = req.getParameter("size");
		ExecPerl ep = injector.getInstance(ExecPerl.class);//new ExecPerl("resize.pl",scs.getAssetSavePath(),a.getFilePath());
		String assetroot = siteConfiger.getValue(SiteConfigerKeyName.ASSET_ROOT);
    	try {
			ep.exec(new File(fps.getWebinfDir(),"resize.pl").getAbsolutePath(),assetroot,a.getFilePath(),size);
		} catch (Exception e) {
			e.printStackTrace();
		}
    	autils.writeHtmlResponseWithTemplate(res,"<img src=\"" + a.getUrl(size)  + "\"/>");
	}
	
	@Override
	public void doPost(HttpServletRequest req, HttpServletResponse res)
		throws ServletException, IOException {
		
		res.setContentType("text/html;charset=UTF-8");   
		res.setCharacterEncoding("UTF-8");
		
		boolean isMultipart = ServletFileUpload.isMultipartContent(req);
		
		if(isMultipart){
			FileUploader nfu = injector.getInstance(FileUploader.class);
			nfu.process();
		}
	}
}
